package com.hkts.naturalgasauthentication.base.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hkts.naturalgasauthentication.base.dao.DepartmentDao;
import com.hkts.naturalgasauthentication.base.dao.HontUserDao;
import com.hkts.naturalgasauthentication.base.dao.ManagementBaseDao;
import com.hkts.naturalgasauthentication.base.dao.mapper.PermissionMapper;
import com.hkts.naturalgasauthentication.base.dao.mapper.UserMapper;
import com.hkts.naturalgasauthentication.base.dao.mapper.UserRoleMapper;
import com.hkts.naturalgasauthentication.base.entity.Department;
import com.hkts.naturalgasauthentication.base.entity.Permission;
import com.hkts.naturalgasauthentication.base.entity.Role;
import com.hkts.naturalgasauthentication.base.entity.User;
import com.hkts.naturalgasauthentication.base.notification.SubscribeMessageVO;
import com.hkts.naturalgasauthentication.base.notification.WxMssVo;
import com.hkts.naturalgasauthentication.base.service.HontUserService;
import com.hkts.naturalgasauthentication.common.constant.CommonConstant;
import com.hkts.naturalgasauthentication.common.vo.SearchVo;
import com.hkts.naturalgasauthentication.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
@Transactional
public class HontUserServiceimpl implements HontUserService {

    @Autowired
    private HontUserDao userDao;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    public ManagementBaseDao getRepository() {
        return userDao;
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User>  query=new QueryWrapper<User>();
        query.lambda().eq(User::getUserName,username);
        User user = userMapper.selectOne(query);
        // 关联角色
      /*  List<Role> roleList = userRoleMapper.findByUserId(user.getId());
        user.setRoles(roleList);*/
        // 关联权限菜单
       /* List<Permission> permissionList = permissionMapper.findByUserId(user.getId());
        user.setPermissions(permissionList);*/
        return user;
    }

    @Override
    public User findByNickname(String username) {
        return userDao.findByNickName(username);
    }

    @Override
    public List<User> findByNicknameLike(String username) {
        return userDao.findByNickNameLike("%"+username+"%");
    }

    @Override
    public List<User> getUsersByuserIds(List<String> ids) {
        return userDao.getUsersByuserIds(ids);
    }

    @Override
    public User findByMobile(String mobile) {

        return userDao.findByMobile(mobile);
    }

    @Override
    public User findByEmail(String email) {

        return userDao.findByEmail(email);
    }

    @Override
    public Page<User> findByCondition(User user, SearchVo searchVo, Pageable pageable) {
        log.info(user.toString());
        User currUser = securityUtil.getCurrUser();
        user.setCompanyId(currUser.getCompanyId());
        return userDao.findAll(new Specification<User>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Path<String> usernameField = root.get("userName");
                Path<String> mobileField = root.get("mobile");
                Path<String> emailField = root.get("email");
                Path<String> nickNamelField = root.get("nickName");
                Path<String> departmentIdField = root.get("departmentId");
                Path<String> sexField = root.get("sex");
                Path<Date> createTimeField = root.get("createTime");
                Path<String> companyIdField = root.get("companyId");
                Path<Integer> typeField = root.get("type");
                Path<Integer> delFlagField = root.get("delFlag");
                List<Predicate> list = new ArrayList<Predicate>();

                //模糊搜素
                if (StrUtil.isNotBlank(user.getUserName())) {
                    list.add(cb.like(usernameField, '%' + user.getUserName() + '%'));
                }
                //昵称
                if (StrUtil.isNotBlank(user.getNickName())) {
                    list.add(cb.like(nickNamelField, '%' + user.getNickName() + '%'));
                }
                if (StrUtil.isNotBlank(user.getMobile())) {
                    list.add(cb.like(mobileField, '%' + user.getMobile() + '%'));
                }
                if (StrUtil.isNotBlank(user.getEmail())) {
                    list.add(cb.like(emailField, '%' + user.getEmail() + '%'));
                }

                //部门
                if (StrUtil.isNotBlank(user.getDepartmentId())) {
                    list.add(cb.equal(departmentIdField, user.getDepartmentId()));
                }

                //性别
                if (StrUtil.isNotBlank(user.getSex())) {
                    list.add(cb.equal(sexField, user.getSex()));
                }
                //公司
                if (StrUtil.isNotBlank(user.getCompanyId())) {
                    list.add(cb.like(companyIdField, user.getCompanyId()+ '%'));
                }
                //创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }
                //用户分类货主还是管理员
                if (user.getType() != null) {
                    list.add(cb.equal(typeField, user.getType()));
                }
                //未删除用户显示
                list.add(cb.equal(delFlagField, CommonConstant.STATUS_NORMAL));
                /*//前后台标识
                if(user.getUserFlag()!=null){
                    list.add(cb.equal(flagField, user.getUserFlag()));
                }*/
                //数据权限
                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public List<User> findByDepartmentId(String departmentId) {

        return userDao.findByDepartmentId(departmentId);
    }

    @Override
    public List<User> getAll() {
        return userDao.findAll();
    }

    @Override
    public User cutomerfindByMobile(String mobile) {
        List<User> all = userDao.findAll();
        User user = null;
        /*for(int i=0;i<all.size();i++){
            log.info(all.get(i).getMobile());
            if(all.get(i).getMobile()!=null&&all.get(i).getMobile().equals(mobile)){
                boolean equals = all.get(i).getMobile().equals(mobile);
                log.info(""+equals);
                if(all.get(i).getUserFlag()==1){
                    user=all.get(i);
                    break;
                }
            }
        }*/

        //  User user = userDao.findByMobile(mobile);
        if (user == null) {
            return null;
        }
        // 关联部门
        if (StrUtil.isNotBlank(user.getDepartmentId())) {
            Department department = departmentDao.findById(user.getDepartmentId()).orElse(null);
            if (department != null) {
                user.setDepartmentTitle(department.getTitle());
            }
        }
        // 关联角色
        List<Role> roleList = userRoleMapper.findByUserId(user.getId());
        user.setRoles(roleList);
        // 关联权限菜单
        List<Permission> permissionList = permissionMapper.findByUserId(user.getId());
        user.setPermissions(permissionList);
        return user;
    }

    @Override
    public User findUserById(String id) {
        return get(id);
    }

    /**
     * 消息推送
     *
     * @return
     */
    public String getAccessToken() {
        if (redisTemplate.opsForValue().get("access_token") != null) {
            System.out.println(redisTemplate.opsForValue().get("access_token"));
            return redisTemplate.opsForValue().get("access_token");
        }
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wx3e1d6f5c08a3aac7");
        params.put("APPSECRET", "b8e6c6441a3a26aaf3cbe5774483d544");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String Access_Token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        redisTemplate.opsForValue().set("access_token", Access_Token, 7140, TimeUnit.SECONDS);
        return Access_Token;
    }

    @Override
    public String sendEnd(String[] o) {
        User currUser = securityUtil.getCurrUser();
        String nickName = currUser.getNickName();
        if (o.length > 0 || o != null) {
            for (int i = 0; i < o.length; i++) {
                RestTemplate restTemplate = new RestTemplate();
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
                SubscribeMessageVO bean = new SubscribeMessageVO();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String format = formatter.format(new Date());
                bean.setThing1(new SubscribeMessageVO.Thing1(nickName));
                bean.setTime2(new SubscribeMessageVO.Time2(format));
                WxMssVo wxMssVO = new WxMssVo();
                wxMssVO.setTouser(o[i]);
                wxMssVO.setTemplate_id("eelhtBbVOfpyCU13R0paxTenquHq81IJRN6HX7tPOi8");//模板id号码
                wxMssVO.setData(bean);
                /*wxMssVO.setAppid("wx3e1d6f5c08a3aac7");*/
                try {
                    ResponseEntity<String> responseEntity =
                            restTemplate.postForEntity(url, wxMssVO, String.class);
                    return responseEntity.getBody();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /*
     *
     * */
    @Override
    public void sendMessageByUserId(String userId, String msg) {
        User one = userDao.getOne(userId);
        if (one.getOpenId() == null) {
            throw new RuntimeException("货主无openId");
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        SubscribeMessageVO bean = new SubscribeMessageVO();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(new Date());
        bean.setThing1(new SubscribeMessageVO.Thing1(msg));
        bean.setTime2(new SubscribeMessageVO.Time2(format));
        WxMssVo wxMssVO = new WxMssVo();
        wxMssVO.setTouser(one.getOpenId());
        wxMssVO.setTemplate_id("eelhtBbVOfpyCU13R0paxTenquHq81IJRN6HX7tPOi8");//模板id号码
        wxMssVO.setData(bean);
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVO, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public User updateOpenId(User user) {
        userDao.updateopenId(user.getOpenId(), user.getId());
        return userDao.findById(user.getId()).orElse(null);
    }

    /**
     * 功能描述:
     *
     * @return: boolean
     * @Author: 杨春科
     * @Date: 2021-08-17 10:33
     * @Description //TODO
     */
    @Override
    public boolean findByMobileAndId(String id, String mobile) {
        List<User> list = userDao.findByMobileAndId(id, mobile);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean getUserByOpenId(String openId) {
        User user=  userDao.findByOpenId(openId);
        if(user!=null){
            return true;
        }
        return false;
    }
}
